<template>
  <div class="app-container">
    <div class="control-panel">
      <el-button @click="trainButtonClick">🚂 {{ isAddingTrain ? "完成放置" : "放置火车" }}</el-button>
      <el-button @click="resetView">🔄 还原视图</el-button>
      <span class="status">{{ statusText }}</span>
    </div>
    <el-row :gutter="20">

      <el-col :span="24">
        <div id="container" ref="container">
          <svg id="svg-container" ref="svg_container" xmlns="http://www.w3.org/2000/svg"
               style="width: 33.1102in;height: 23.3858in;" viewBox="0 0 2383.94 1683.78" :style="{
          transform: `translate(${viewState.x}px, ${viewState.y}px) scale(${viewState.scale})`,
          cursor: svgCursor
        }">
            <image id="background" :href="drawingUrl" width="100%" preserveAspectRatio="xMidYMid meet"></image>
            <line
              v-for="line in lines"
              class="svg-line"
              :line-code="line.lineCode"
              :line_name="line.lineName"
              :data-id="line.id"
              :key="line.id"
              :x1="line.x1"
              :y1="line.y1"
              :x2="line.x2"
              :y2="line.y2"
              @click="addTrain"
              :stroke="line.color">
            </line>
            <!-- 动态创建多个火车 -->
            <g v-for="train in trainList" :key="train.id" @click="trainClick(train)"
               :transform="`translate(${train.placement})`"
               v-html="getTrainIconData(train.iconId)">
            </g>
          </svg>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      title="放置火车"
      :visible.sync="controlTrainDialogVisible"
      width="30%"
    >
      <el-form ref="controlTrainForm" :model="controlTrainForm" :rules="controlTrainFromRules" label-width="80px">
        <el-form-item label="火车类型" prop="iconId">
          <el-select v-model="controlTrainForm.iconId" placeholder="请选择火车类型">
            <el-option-group
              v-for="group in trainModelList"
              :key="group.model.trainName"
              :label="group.model.trainName">
              <el-option
                v-for="item in group.iconList"
                :key="item.id"
                :label="item.iconName"
                :value="item.id">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="机车号" prop="trainNumber">
          <el-input v-model="controlTrainForm.trainNumber" placeholder="请输入机车号"/>
        </el-form-item>
        <el-form-item label="确认人员" prop="confirmerName">
          <el-input v-model="controlTrainForm.confirmerName" placeholder="请输入确认人员"/>
        </el-form-item>
        <el-form-item label="操作说明" prop="description">
          <el-input v-model="controlTrainForm.description" type="textarea" placeholder="请输入本次操作说明"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitControlTrainForm">确 定</el-button>
        <el-button @click="cancelControlTrainForm">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="火车信息"
      :visible.sync="trainInfoDialogVisible"
      width="30%"
      custom-class="train-info-dialog"
    >
      <div class="train-info-box">
        <div class="train-info-item">
          <span class="train-info-item-name">操作员：</span>
          <span class="train-info-item-value">{{ selectTrainInfo.crewName || '--' }}</span>
        </div>
        <div class="train-info-item">
          <span class="train-info-item-name">机车号：</span>
          <span class="train-info-item-value">{{ selectTrainInfo.trainNumber || '--' }}</span>
        </div>
        <div class="train-info-item">
          <span class="train-info-item-name">入场时间：</span>
          <span class="train-info-item-value">
          {{ selectTrainInfo.entryTime || '--' }}
          <span v-if="selectTrainInfo.entryTime" class="duration-text">
            ，已经入场 {{ calculateDuration(selectTrainInfo.entryTime) }}
          </span>
        </span>
        </div>
        <div class="train-info-item">
          <span class="train-info-item-name">确认员：</span>
          <span class="train-info-item-value">{{ selectTrainInfo.confirmerName || '--' }}</span>
        </div>
        <div class="train-info-item">
          <span class="train-info-item-name">所在车道：</span>
          <span class="train-info-item-value">
          <el-tag v-if="selectTrainInfo.lineCode" size="small" type="primary">
            {{ selectTrainInfo.lineCode }}
          </el-tag>
          <span v-else>--</span>
        </span>
        </div>
        <div class="train-info-item full-width">
          <span class="train-info-item-name">操作说明：</span>
          <span class="train-info-item-value description-text">
          {{ selectTrainInfo.description || '暂无说明' }}
        </span>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onExitTrain">离开</el-button>
        <el-button @click="cancelTrainInfo">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {delStation_drawing, getStation_drawingByUser} from "@/api/system/station_drawing"

import {getAll} from "@/api/system/train_icon"
import {getStockyard_train_positionByDrawing, enterTrain, exitTrain} from "@/api/system/stockyard_train_position"

import {
  getLinesByDrawingId
} from "@/api/system/single_line_annotation";


export default {
  name: "stockyard_control",
  data() {
    return {
      // 遮罩层
      loading: true,
      //
      drawingInfo: {},
      statusText: '就绪',
      svgCursor: '',
      drawingUrl: '',
      viewState: {x: 0, y: 0, scale: 1},
      isDragging: false,
      lastX: 0,
      lastY: 0,
      isAnnotating: false,
      lines: [],
      isAddingTrain: false,
      trainModelList: [],
      trainIconMap: {},
      trainList: [],
      controlTrainDialogVisible: false,
      controlTrainForm: {},
      controlTrainFromRules: {
        confirmerName: [{required: true, message: "确认人员不能为空", trigger: "blur"}],
        trainNumber: [{required: true, message: "机车号不能为空", trigger: "blur"}],
        iconId: [{required: true, message: "火车型号不能为空", trigger: "blur"}],
        description: [{required: true, message: "操作说明不能为空", trigger: "blur"}]
      },
      trainInfoDialogVisible:false,
      selectTrainInfo:{}
    }
  },
  computed: {
    container() {
      return this.$refs.container
    },
    svgContainer() {
      return this.$refs.svg_container
    }

  },
  mounted() {
    this.container.addEventListener('wheel', this.containerWheel, true); //滚轮缩放
    this.svgContainer.addEventListener('mousedown', this.svgContainerMousedown, true); // 拖拽
    document.addEventListener('mousemove', (e) => {
      if (!this.isDragging) return;
      this.viewState.x = e.clientX - this.lastX;
      this.viewState.y = e.clientY - this.lastY;
    });
    document.addEventListener('mouseup', () => {
      this.isDragging = false;
      this.svgCursor = this.svgCursor ? 'crosshair' : 'grab';
    });
  },
  beforeMount() {
    // window.addEventListener('resize', this.updateTransform)
  },
  beforeDestroy() {
    // window.removeEventListener('resize', this.updateTransform)
  },
  created() {
    this.initData();
  },
  methods: {
    // 初始化数据 获取站点图纸
    initData() {
      getStation_drawingByUser().then(response => {
        // 获取图纸信息
        if (response?.data && response.data.length >= 1) {
          this.drawingUrl = process.env.VUE_APP_BASE_API + response.data[0].basicDrawingInfo;
          this.drawingInfo = response.data[0];
          this.getLines();
        }
      })
      // 获取图标信息
      getAll().then(response => {
        if (response?.data && response.data.length >= 1) {
          const _trainModelList = response.data;
          this.trainModelList = _trainModelList;
          let _trainIconMap = {};
          _trainModelList.forEach(trainModel => {
            if (trainModel.iconList) {
              trainModel.iconList.forEach(icon => {
                _trainIconMap[icon.id] = icon;
              })
            }
          })
          this.trainIconMap = _trainIconMap;
        }
      })
    },
    getLines() {
      getLinesByDrawingId(this.drawingInfo.id).then(response => {
        console.log(response);
        if (response?.data) {
          this.lines = response.data;
          this.getTrainData();
        }
      })
    },
    getTrainData() {
      getStockyard_train_positionByDrawing(this.drawingInfo.id).then(response => {
        console.log(response);
        if (response?.data) {
          this.trainList = response.data;
        }
      })
    },
    trainButtonClick() {
      if (!this.isAddingTrain) {
        this.statusText = "火车放置模式，可点击线路放置火车";
        this.isAddingTrain = true;
      } else {
        this.statusText = "整备场预览模式";
        this.isAddingTrain = false;
      }
    },
    addTrain(e) {
      console.log("addTrain", this.isAddingTrain, e.clientX, e.clientY, this.screenToSvg(e.clientX, e.clientY), e.currentTarget.getAttribute('data-id'), e);
      if (!this.isAddingTrain) {
        console.log("当前不是放置火车模式，", e.clientX, e.clientY, e);
        return;
      }
      const svgPlacement = this.screenToSvg(e.clientX, e.clientY);
      const lineId = e.currentTarget.getAttribute('data-id');
      const lineCode = e.currentTarget.getAttribute('line-code');

      this.controlTrainDialogVisible = true;
      this.controlTrainForm = {
        "deptId": this.drawingInfo.deptId,
        "drawingId": this.drawingInfo.id,
        "lineId": lineId,
        "lineCode": "shape115-1265",
        "trainModelId": null,
        "iconId": null,
        "trainStatus": "APPROVED",
        "placement": svgPlacement.x + "," + svgPlacement.y,
        "trainNumber": null,
        "crewId": null,
        "crewWorkNumber": null,
        "crewName": null,
        "confirmerId": null,
        "confirmerWorkNumber": null,
        "confirmerName": null,
        "entryTime": null,
        "approvalTime": null,
        "estimatedDepartureTime": null,
        "currentApproverId": null,
        "currentApproverWorkNumber": null,
        "currentApproverName": null,
        "description": null,
        "standardParams": null,
        "customParams": null,
        "ext": null
      }
    },
    submitControlTrainForm() {
      this.$refs["controlTrainForm"].validate(valid => {
        if (valid) {

          const _iconInfo = this.trainIconMap[this.controlTrainForm.iconId]
          this.controlTrainForm.trainModelId = _iconInfo.trainModelId;
          enterTrain(this.controlTrainForm).then(response => {
            this.$modal.msgSuccess("操作成功")
            this.controlTrainDialogVisible = false
            this.getTrainData();
          })
        }
      })
    },
    cancelControlTrainForm() {
      this.controlTrainDialogVisible = false;
    },
    trainClick(train) {
      if(this.isAddingTrain){
        console.log("正在放置新的小火车，请勿点击在途车辆~")
        return ;
      }
      this.selectTrainInfo = train;
      this.trainInfoDialogVisible = true;

    },
    getTrainIconData(id) {
      return this.trainIconMap[id]["iconData"];
    },
    onExitTrain(){
      // this.$modal.confirm(this.selectTrainInfo.trainNumber+'确定要离开整备场了嘛？').then(function() {
      //   return exitTrain({id:this.selectTrainInfo.id})
      // }).then(() => {
      //   this.$modal.msgSuccess("操作成功");
      //   this.trainInfoDialogVisible = false;
      //   this.selectTrainInfo = {};
      //   this.getTrainData();
      // }).catch(() => {})
      exitTrain({id:this.selectTrainInfo.id}).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.trainInfoDialogVisible = false;
        this.selectTrainInfo = {};
        this.getTrainData();
      })

    },
    cancelTrainInfo(){
      this.trainInfoDialogVisible = false;
      this.selectTrainInfo = {};
    },
    screenToSvg(clientX, clientY) {
      const pt = this.svgContainer.createSVGPoint();
      pt.x = clientX;
      pt.y = clientY;
      const svgP = pt.matrixTransform(this.svgContainer.getScreenCTM().inverse());
      return {
        x: svgP.x,
        y: svgP.y
      };
    },
    containerWheel(e) { // 中心底图缩放事件

      e.preventDefault();
      const scaleFactor = e.deltaY > 0 ? 0.9 : 1.1;
      const newScale = this.viewState.scale * scaleFactor;

      if (newScale < 0.3 || newScale > 10) return;

      const rect = this.container.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      this.viewState.x -= (mouseX - this.viewState.x) * (scaleFactor - 1);
      this.viewState.y -= (mouseY - this.viewState.y) * (scaleFactor - 1);
      this.viewState.scale = newScale;
    },
    svgContainerMousedown(e) { // 中心底图拖拽事件
      if (this.isAnnotating || e.target.classList.contains('line')) return;
      this.isDragging = true;
      this.lastX = e.clientX - this.viewState.x;
      this.lastY = e.clientY - this.viewState.y;
      this.svgCursor = 'grabbing';
    },
    resetView() { // 还原试图
      this.viewState = {x: 0, y: 0, scale: 1};
    },
    calculateDuration(entryTime) {
      // 计算入场时间的持续时间
      const entry = new Date(entryTime);
      const now = new Date();
      const diffMs = now - entry;

      const hours = Math.floor(diffMs / (1000 * 60 * 60));
      const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));

      if (hours > 0) {
        return `${hours}小时${minutes}分钟`;
      } else {
        return `${minutes}分钟`;
      }
    },

  }
}
</script>

<style scoped lang="scss">
body {
  margin: 0;
  padding: 20px;
  font-family: Arial, sans-serif;
  overflow: hidden;
}

#container {
  width: 100%;
  height: 100vh;
  border: 1px solid #ccc;
  overflow: hidden;
  position: relative;
  touch-action: none;
}

#svg-container {
  width: 100%;
  height: 100%;
  cursor: grab;
  //background-color: #f8f8f8;
}

#svg-container:active {
  cursor: grabbing;
}

.svg-line {
  stroke-width: 6;
  stroke: red;
  fill: none;
}

.svg-line:hover {
  stroke-width: 8;
  stroke: aqua;
}

.temp {
  stroke: blue;
  stroke-dasharray: 4, 4;
}

.control-panel {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

button {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

select, input {
  padding: 8px;
  font-size: 14px;
}

.status {
  font-size: 14px;
  color: #555;
  margin-left: auto;
}
.train-info-box {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 0;
  border: 1px solid #e4e7ed;
}

.train-info-item {
  display: flex;
  align-items: flex-start;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
  transition: background-color 0.2s ease;
}

.train-info-item:hover {
  background-color: #fafbfc;
}

.train-info-item:last-child {
  border-bottom: none;
}

.train-info-item.full-width {
  align-items: flex-start;
}

.train-info-item-name {
  min-width: 80px;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  line-height: 1.5;
  margin-right: 12px;
  flex-shrink: 0;
}

.train-info-item-value {
  flex: 1;
  font-size: 14px;
  color: #303133;
  line-height: 1.5;
  word-break: break-word;
}

.duration-text {
  color: #67C23A;
  font-weight: 500;
}

.description-text {
  background: white;
  padding: 12px;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
  font-style: italic;
  color: #606266;
  line-height: 1.6;
}
</style>
